package controllers;

import helpers.CrawlerDomainHelper;
import helpers.IpHelper;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import debugs.IpAddressDebug;

import entities.IpAddress;

import models.IpAddressModel;

public class CheckIpServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String ip = (String) request.getParameter("q");
		
		if (ip == null || ip.isEmpty()) {
			ip = request.getRemoteAddr();
		} else if (ip != null && !IpHelper.checkIsIp(ip)) {
			request.setAttribute("error", "Please enter ip address valid.");
		}
		
		IpAddressModel ipAddressModel = IpAddressModel.getInstance();
		IpAddress ipAddress = ipAddressModel.get(ip);
		
		if (ipAddress == null) {
			ipAddress = new IpAddress();
			ipAddress.setIp(ip);
			CrawlerDomainHelper crawler = new CrawlerDomainHelper();
			ipAddress = crawler.getIp(ipAddress);
			if (ipAddress != null) {
				ipAddressModel.insert(ipAddress);
			}
		}
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("ip", ip);
		request.setAttribute("ipAddress", ipAddress);
		try {
			request.getRequestDispatcher("/pages/checkip.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
